#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import remove_zero
current_dir = os.getcwd()
os.chdir(".")
import json
import socket
import time
import sys
import os
import argparse
import base64

'''
可选命令行：
..\d_shake_raw_ch01_h01(2).json -field_name "bin_data"
..\d_shake_raw_ch01_h01(2).json -field_name "bin_data" -decode_base64

'''


def mysql_json_from_db_records_top_name():
    return "RECORDS";

def ba2file(binary_array, filename):
    # 使用二进制写入模式打开文件
    with open(filename, "wb") as file:
        file.write(binary_array)
    print("Binary array has been saved to", filename)

def sendByteArrayToUdpPort(ba, ipaddr):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(ba, ipaddr)

def json2Udp(filename, ip, port, playbackSpeedInS, isCycle):
    print(filename, ip, port, playbackSpeedInS, isCycle)
    while(True):
        with open(filename, 'r') as file:
            json_data = file.read()
            parsed_data = json.loads(json_data)
        print("record cnts of json file", len(parsed_data[mysql_json_from_db_records_top_name()]))
        records = parsed_data[mysql_json_from_db_records_top_name()]
        for r in records:
            print(r)
            ba = json.dumps(r).encode('utf-8')
            sendByteArrayToUdpPort(ba, (ip, port))
            ba2file(ba, "./data/record_from_db.bin");
            remove_zero.move_data_zero_to32768("./data/record_from_db.bin")
            time.sleep(playbackSpeedInS)
        if(not isCycle): break;

def jsonOfShakeRawSampleData2Udp(filename, ip, port, playbackSpeedInS, isCycle, fieldName, isDecodeFromBase64):
    print(filename, ip, port, playbackSpeedInS, isCycle)
    while(True):
        with open(filename, 'r') as file:
            json_data = file.read()
            parsed_data = json.loads(json_data)
        print("record cnts of json file", len(parsed_data[mysql_json_from_db_records_top_name()]))
        records = parsed_data[mysql_json_from_db_records_top_name()]
        for r in records:
            print(r)
            ba = json.dumps(r[fieldName]).encode('utf-8')
            if(isDecodeFromBase64):
                ba = base64.b64decode(ba)
            sendByteArrayToUdpPort(ba, (ip, port))
            ba2file(ba, "./data/record_from_db.bin");
            remove_zero.move_data_zero_to32768("./data/record_from_db.bin")
            time.sleep(playbackSpeedInS)
        if(not isCycle): break;

def printUsage():
    print("Usage: Json2Udp -ip <127.0.0.1> -port <12345> -delay <5> -c <json_file>")
    print(" ip,port: udp target port.[default: 127.0.0.1:12345]");
    print(" -delay <n>, nsecs to emit the next record.[default:5 sec]");
    print(" -c, cycle mode, endless[ default: one shot no cycle]");
    print(" -field_name <bin_field_name> parse bin_data in base64 type transfer to bin, out]")
    print(" -decode_base64 [default:false]")

def parseParametersThenExec(args, filename, ip, port, delay, endless):
    # 创建一个 argparse 解析器对象
    parser = argparse.ArgumentParser()
    # 添加命令行参数
    parser.add_argument('-ip', '--ip_address', type=str, help='IP address')
    parser.add_argument('-port', '--port_number', type=int, help='Port number')
    parser.add_argument('-delay', '--delay_time', type=int, help='Delay time')
    parser.add_argument('-c', '--cycle_mode', action='store_true', help='Cycle mode')
    parser.add_argument('json_file', type=str, help='Json file')
    parser.add_argument('-field_name', '--field_name', type=str, help='Bin field name')
    parser.add_argument('-decode_base64', '--decode_base64', action='store_true', help='base64解码')
    
    # 解析命令行参数
    args = parser.parse_args()
    # 打印结果
    if(args.json_file is not None):
        filename = args.json_file    
        print("Json File: ", args.json_file)
    if(args.ip_address is not None):
        ip = args.ip_address    
        print("IP address: ", args.ip_address)
    if(args.port_number is not None):
        port = args.port_number
        print("Port number: ", args.port_number)
    if(args.delay_time is not None):
        delay=args.delay_time
        print("Delay time: ", args.delay_time)
    if(args.cycle_mode is not None):
        endless = args.cycle_mode
        print("endless Cycle:", args.cycle_mode)
    if os.path.exists(filename):
        if(args.field_name is not None):
            fieldName = args.field_name;
            isDecodeFromBase64 = False
            if(args.decode_base64 is not None):
                isDecodeFromBase64 = True
                print("DecodeFromBase64:", args.decode_base64)
            jsonOfShakeRawSampleData2Udp(filename, ip, port, delay, endless, fieldName, isDecodeFromBase64)
            
        else:
            json2Udp(filename, ip, port, delay, endless)
    
        
# 获取命令行参数列表
args = sys.argv

# 打印命令行参数
print("命令行参数列表：", args)

# 获取命令行参数的个数
num_args = len(args)
print("命令行参数个数：", num_args)

ip = "127.0.0.1"
port = 12345
delay = 5
endless = False
filename = "d_shake_raw_ch01_h01(2).json"
# 检查是否有足够的命令行参数
if num_args == 1:
    printUsage();
else:
    if num_args == 2:
        filename = args[2-1];
        if not os.path.exists(filename):
            printUsage();
        else:
            json2Udp(filename, ip, port, delay, endless)
    else:
        if(not parseParametersThenExec(args[1:], filename, ip, port, delay, endless)):
            print("file ", filename, " doesn't exists");
